package com.edu.fafu.studentrepair.fragments;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.edu.fafu.studentrepair.MainActivity;
import com.edu.fafu.studentrepair.R;
import com.edu.fafu.studentrepair.command.Dictionary;
import com.edu.fafu.studentrepair.command.LocalDataStream;
import com.edu.fafu.studentrepair.command.ReJsonRsp;
import com.edu.fafu.studentrepair.command.UploadUtil;
import com.edu.fafu.studentrepair.entitys.PublicRepair;
import com.edu.fafu.studentrepair.entitys.StudentRepair;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static com.edu.fafu.studentrepair.command.Dictionary.Upload.CODE_PHOTO_CAMERA;
import static com.edu.fafu.studentrepair.command.Dictionary.Upload.CODE_PHOTO_SELECT;
import static com.edu.fafu.studentrepair.command.UnitChange.dipToPx;

public class ApplyPublicFragment extends Fragment {
    private String img_src;
    private EditText apply_iden;
    private EditText apply_addr;
    private EditText apply_msg;
    private LinearLayout apply_layout_fileUpload;
    private ImageView apply_layout_camera;
    private ImageView apply_layout_pic;
    private ImageView apply_exchange;
    private Button apply_btn_submit;
    private Uri ImageUri;
    private int count = 0;
    public static final int MAX_NUM = 2;
    private ProgressDialog pd;
    private String studentAddr;
    private int renderAddr = 1;
    private int showpd = 2;
    private int dismisspd = 3;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == renderAddr) {

            }else if (msg.what == showpd){
                showPD();
            }else if (msg.what == dismisspd){
                dismissPD();
            }
        }
    };
    private void cleanAll(){
        apply_iden.setText("");

        apply_addr.setText("");
        apply_msg.setText("");
        apply_layout_fileUpload.removeAllViews();
    }
    private String pdTitle;
    private String pdMsg;
    private  void showPD(){
        pd= ProgressDialog.show(getActivity(), pdTitle, pdMsg);
    }
    private void dismissPD(){
        pd.dismiss();
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.add_new_repair_public,container,false);
        apply_iden = view.findViewById(R.id.apply_iden_public);
        apply_addr = view.findViewById(R.id.apply_addr_public);

        apply_msg = view.findViewById(R.id.apply_msg_public);
        apply_layout_fileUpload = view.findViewById(R.id.apply_layout_fileUpload_public);
        apply_layout_camera = view.findViewById(R.id.apply_layout_camera_public);
        apply_layout_pic = view.findViewById(R.id.apply_layout_pic_public);
        apply_btn_submit = view.findViewById(R.id.apply_btn_submit_public);
        apply_exchange = view.findViewById(R.id.apply_exchange_public);
        apply_exchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity mainActivity = (MainActivity) getActivity();
                int oLast = mainActivity.getLastfragment();
                mainActivity.setLastfragment(Dictionary.Page.FRAGMENT_APPLY);
                mainActivity.switchFragment(oLast,Dictionary.Page.FRAGMENT_APPLY);
            }
        });
        try {
            String info = LocalDataStream.read(getActivity().openFileInput("data"));
            if(info.split("_")[3].equals("0"))
                apply_btn_submit.setEnabled(false);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        apply_layout_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraImg();
            }
        });

        apply_iden.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                } else {
                    // 此处为失去焦点时的处理内容
//                    查询地址
                    final String iden = apply_iden.getText().toString();
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            final Request request = new Request.Builder()
                                    .url(Dictionary.url.head+"app/getAddr?studentId="+iden)
                                    .get()
                                    .build();
                            OkHttpClient okHttpClient = new OkHttpClient();
                            Response response = null;
                            try {
                                response = okHttpClient.newCall(request).execute();
                                String json = response.body().string();
                                JSONObject jsonObject = (JSONObject) JSON.parse(json);
                                studentAddr = (String) jsonObject.get("data");
                                Message message = new Message();
                                message.what=renderAddr;
                                handler.sendMessage(message);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    Thread thread = new Thread(runnable);
                    thread.start();

                }
            }
        });
        apply_layout_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImg();
            }
        });
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (getActivity().checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        apply_btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        pdTitle = "报修提交";
                        pdMsg = "图片上传中…";
                        Message message = new Message();
                        message.what=showpd;
                        handler.sendMessage(message);

                        Integer count = apply_layout_fileUpload.getChildCount();
                        List<Integer> picids = new ArrayList<>();
                        for(int i = 0;i<count;i++){
                            View imgView = apply_layout_fileUpload.getChildAt(i);
                            File file = new File((String) imgView.getTag());
                            Integer id =UploadUtil.uploadImage(file,Dictionary.url.head+"tool/picUpload");
                            picids.add(id);
                            Log.i("file upload", "onClick: .id "+id);
                        }
                        message = new Message();
                        message.what=dismisspd;
                        handler.sendMessage(message);

                        pdTitle = "报修提交";
                        pdMsg = "报修提交中…";
                        message = new Message();
                        message.what=showpd;
                        handler.sendMessage(message);
//                        pd= ProgressDialog.show(getActivity(), "报修提交", "报修提交中…");
//                        提交表单
                        String idenAndpwd = null;
                        try {
                            idenAndpwd = LocalDataStream.read(getActivity().openFileInput("data"));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        String area = idenAndpwd.split("_")[6];
                        PublicRepair publicRepair = new PublicRepair();
                        publicRepair.setApplicantName(apply_iden.getText().toString());
                        publicRepair.setRepairAddr(apply_addr.getText().toString());
                        publicRepair.setArea(area);
                        publicRepair.setPics(picids);
                        publicRepair.setQuestionMsg(apply_msg.getText().toString());
                        String json = JSON.toJSONString(publicRepair);
                        Log.i("apply repair", "run: json");
                        RequestBody requestBody =RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
                        OkHttpClient okHttpClient = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(Dictionary.url.head+"app/studentRepair")
                                .post(requestBody)
                                .build();
                        try {
                            Response response = okHttpClient.newCall(request).execute();
//                            Log.i("apply repair", "run: "+response.body().string());
                            json = response.body().string();
                            ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                            Integer code = reJsonRsp.getCode();
                            String msg ="";
                            if(!code.equals(0))
                                msg = reJsonRsp.getMsg();
                            else {
                                msg = "申报成功";
                                cleanAll();
                            }
                            Toast toast =Toast.makeText(getActivity(),msg,Toast.LENGTH_LONG);
                            toast.show();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        message = new Message();
                        message.what=dismisspd;
                        handler.sendMessage(message);
                    }
                };
                Thread thread = new Thread(runnable);
                thread.start();
            }
        });
        return view;
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden)  return;//隐藏页面，不操作
        count = 0;
        ((EditText)getActivity().findViewById(R.id.apply_iden_public)).setText("");
        ((EditText)getActivity().findViewById(R.id.apply_addr_public)).setText("");
        ((EditText)getActivity().findViewById(R.id.apply_msg_public)).setText("");
        apply_layout_fileUpload.removeAllViews();
    }
    public void selectImg() {
        if(count>=MAX_NUM){
            Toast toast = Toast.makeText(getActivity(),"上传过多",Toast.LENGTH_LONG);
            toast.show();
            return;
        }
        Log.i("apply", "selectImg: ");
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

        startActivityForResult(intent, CODE_PHOTO_SELECT);

    }

    public void cameraImg(){ //调用相机
        if(count>=MAX_NUM){
            Toast toast = Toast.makeText(getActivity(),"上传过多",Toast.LENGTH_LONG);
            toast.show();
            return;
        }
        String fileName = String.valueOf(System.currentTimeMillis())+UUID.randomUUID().toString().substring(0,3)+".jpg";
        File outputImage = new File(getActivity().getExternalCacheDir(), fileName);
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //如果android7.0以上的系统，需要做个判断

        if (Build.VERSION.SDK_INT >= 24) {
            ImageUri = FileProvider.getUriForFile(getActivity(), "com.edu.fafu.studentrepair", outputImage);//7.0
        } else {
            ImageUri = Uri.fromFile(outputImage); //7.0以下
        }
        //利用隐式Intent 打开系统相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageUri);
        startActivityForResult(intent, CODE_PHOTO_CAMERA);//这里的TAKE_PHOTO是定义的一个静态常数变量
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CODE_PHOTO_SELECT:
                count++;
                switch (resultCode) {
                    case RESULT_OK:
                        Uri uri = data.getData();
                        img_src = uri.getPath();//这是本机的图片路径
                        ContentResolver cr = getActivity().getContentResolver();
                        try {
                            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                            /* 将Bitmap设定到ImageView */
//                            imageView.setImageBitmap(bitmap);
                            final ImageView imageView = new ImageView(getActivity());

                            imageView.setImageBitmap(bitmap);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
                            params.weight = (int) dipToPx(getActivity(), 100f);
                            params.height = (int) dipToPx(getActivity(), 100f);
                            params.gravity = Gravity.LEFT;
                            apply_layout_fileUpload.addView(imageView,params);
                            String[] proj = {MediaStore.Images.Media.DATA};
                            CursorLoader loader = new CursorLoader(getContext(), uri, proj, null, null, null);
                            Cursor cursor = loader.loadInBackground();
                            if (cursor != null) {
                                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                cursor.moveToFirst();
                                img_src = cursor.getString(column_index);//图片实际路径
                                imageView.setTag(img_src);
                            }
                            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                                @Override
                                public boolean onLongClick(View v) {
                                    apply_layout_fileUpload.removeView(imageView);
                                    count --;
                                    return true;
                                }
                            });
                            cursor.close();

                        } catch (FileNotFoundException e) {
                            Log.e("Exception", e.getMessage(), e);
                        }
                        break;
                }
                break;
            case CODE_PHOTO_CAMERA:
                count++;
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(ImageUri));
//                        imageButton.setImageBitmap(bitmap);
                        Log.i("cameraImg", "onActivityResult: "+(new File(ImageUri.toString())).getPath());
                        ContentResolver cr = getActivity().getContentResolver();
                        final ImageView imageView = new ImageView(getActivity());
                        imageView.setImageBitmap(bitmap);

                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
                        params.weight = (int) dipToPx(getActivity(), 100f);
                        params.height = (int) dipToPx(getActivity(), 100f);
                        params.gravity = Gravity.LEFT;
                        apply_layout_fileUpload.addView(imageView,params);

                        imageView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                apply_layout_fileUpload.removeView(imageView);
                                count --;
                                return true;
                            }
                        });
                        Uri imgUri = ImageUri;
                        Log.i("123", "onActivityResult: "+imgUri);
                        imageView.setTag(getRealPath(imgUri));

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;

        }
    }
    private String getRealPath(Uri uri){
        Log.i("change", "getRealPath: "+uri.toString());
        String re="/storage/emulated/0/";
        String uristr = uri.toString();
        uristr = uristr.replace("content://com.edu.fafu.studentrepair/camera_photos/","");
        Log.i("change", "getRealPath: "+re+uristr);
        return re+uristr;
    }
}
